#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
调试导航问题的脚本
"""

import json
import time
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager

def debug_ford_navigation():
    """调试福特网站导航问题"""
    
    # 设置Chrome选项
    chrome_options = Options()
    chrome_options.add_argument('--disable-blink-features=AutomationControlled')
    chrome_options.add_experimental_option("excludeSwitches", ["enable-automation"])
    chrome_options.add_experimental_option('useAutomationExtension', False)
    
    # 设置User-Agent
    chrome_options.add_argument('--user-agent=Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.1 Safari/605.1.15')
    
    # 初始化WebDriver
    service = Service(ChromeDriverManager().install())
    driver = webdriver.Chrome(service=service, options=chrome_options)
    
    try:
        print("🔍 调试福特网站导航...")
        
        # 访问页面
        url = "https://www.ford.co.uk/shop/build-your-ford/ngc2/ice2/model?catalogId=WAEGB-CGE-2022-FocusMCAGBR202450&series=ACMAA_VS-D3&paint=PN4A7&planId=c"
        driver.get(url)
        time.sleep(5)
        
        print(f"当前URL: {driver.current_url}")
        
        # 查找所有车型元素
        print("\n🔍 查找车型元素...")
        model_elements = driver.find_elements(By.CSS_SELECTOR, 'div[data-cy][class*="ProductTile"]')
        print(f"找到 {len(model_elements)} 个车型元素")
        
        for i, element in enumerate(model_elements):
            data_cy = element.get_attribute('data-cy')
            is_displayed = element.is_displayed()
            print(f"  {i+1}. data-cy='{data_cy}', 可见={is_displayed}")
            
            if data_cy == 'Titanium' and is_displayed:
                print(f"\n🎯 分析Titanium车型元素...")
                
                # 查看元素HTML结构
                element_html = element.get_attribute('outerHTML')[:500]
                print(f"元素HTML前500字符: {element_html}")
                
                # 查找所有可点击的子元素
                clickable_elements = element.find_elements(By.CSS_SELECTOR, 'button, a, [role="button"]')
                print(f"\n找到 {len(clickable_elements)} 个可点击元素:")
                
                for j, clickable in enumerate(clickable_elements):
                    try:
                        tag = clickable.tag_name
                        text = clickable.text.strip()
                        classes = clickable.get_attribute('class')
                        href = clickable.get_attribute('href')
                        is_enabled = clickable.is_enabled()
                        is_displayed = clickable.is_displayed()
                        
                        print(f"    {j+1}. {tag}: '{text}' | 类={classes} | href={href} | 可用={is_enabled} | 可见={is_displayed}")
                        
                        # 尝试点击第一个可用的按钮
                        if j == 0 and is_enabled and is_displayed and text:
                            print(f"\n🖱️  尝试点击: {text}")
                            try:
                                driver.execute_script("arguments[0].click();", clickable)
                                time.sleep(3)
                                
                                new_url = driver.current_url
                                print(f"点击后URL: {new_url}")
                                
                                # 检查是否进入了配置页面
                                nav_elements = driver.find_elements(By.CSS_SELECTOR, '[data-testid*="Navigation"], nav')
                                print(f"找到 {len(nav_elements)} 个导航元素")
                                
                                if len(nav_elements) > 0:
                                    nav_text = [elem.text for elem in nav_elements if elem.text.strip()]
                                    print(f"导航内容: {nav_text}")
                                
                                return True
                                
                            except Exception as click_error:
                                print(f"点击失败: {click_error}")
                        
                    except Exception as element_error:
                        print(f"    分析元素失败: {element_error}")
                
                break
        
        return False
        
    except Exception as e:
        print(f"调试过程出错: {e}")
        return False
        
    finally:
        driver.quit()

if __name__ == "__main__":
    debug_ford_navigation()
